<?php
namespace Home\Controller;
use Common\Model\ActivityModel;
use Home\Model\GoodsModel;

/**
 * 搜索
 * @package Home\Controller
 */

class SearchController extends BaseController {

    use ActivityModel;//商品活动价格

    public function __construct()
    {
        parent::__construct();
        $this->local_id = I('local_id', '', 'intval') ?: session('userInfo')['local_id'];
    }

    public function index() {
        $keywords = I('get.keywords', '', 'htmlentities');

        //热门搜索
        if (!$keywords) {
            $hot_search = M('store_search')->where(['local_id'=>$this->local_id, 'state'=>'1'])->order('id desc')->field('id, name')->select();
            $this->assign('hot_search', $hot_search);
            $this->display('empty');
            exit;
        } else {
            //翻页
            $p = max(I('param.p'), 1);
            $num = max(I('param.num', 10, 'intval'), 5);
            $this->assign('p', $p);
            $this->assign('num', $num);
            //排序
            $order_field = I('param.order_field', 'product_id');
            $order = I('param.order', 'desc');
            if ($order_field) {
                switch ($order_field) {
                    case 'saleSort':
                        $order_field = 'sales_num';
                        break;
                    case 'priceSort':
                        $order_field = 'price';
                        break;
                    case 'commentSort':
                        $order_field = 'comment_num';
                        break;
                    default :
                        $order_field = 'store_pid';
                        break;
                }
            }
            //var_dump($order_field);
            $this->assign('order_field', 'a.'.$order_field);
            $this->assign('order', $order);
            $sunxu = $order == 'asc' ? 'desc' : 'asc';
            $this->assign('order', $sunxu);

            /**
            select * from sdb_b2c_store_product a
            LEFT JOIN sdb_b2c_goods b on a.goods_id=b.goods_id
            where a.local_id=1 and b.`name` like '%多芬%'
             */

            if ($order_field && $order) {

                $order = array($order_field => $order);
            }
            $hot_key = I('get.hotKey', 0, 'intval');
            $where[] = ' a.local_id='.$this->local_id;
            $where[] = ' b.disabled="false" ';
            $where[] = ' a.store_status = "true" ';
            $where[] = ' c.product_type_id = 1 ';
            if ($hot_key) {
                $where[] = $this->_hotSearch($hot_key);
            } else {
                $where[] = " a.p_name like '%".$keywords."%' ";
            }
            $count = M('b2c_store_product')
                ->alias('a')
                ->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id')
                ->join(C('DB_PREFIX') . 'b2c_product_relation c on a.product_id=c.product_id')
                ->where($where)
                ->count();
            $totalPage = ceil($count / $num);
            if ($count) {
                $field = 'a.*, b.name,b.spec_info';
                $list = M('b2c_store_product')
                    ->alias('a')
                    ->join(C('DB_PREFIX') . 'b2c_products b on a.product_id=b.product_id')
                    ->join(C('DB_PREFIX') . 'b2c_product_relation c on a.product_id=c.product_id')
                    ->field($field)
                    ->where($where)
                    ->order($order)
                    ->page($p, $num)
                    ->select();
//                print_r($list);
                $goodsids = array_column($list, 'goods_id');
                $images = $this->getProductsImgByGoodsIds($goodsids);

                $GoodsModel = new GoodsModel();
                foreach ($list as $key => &$item) {
                    //商品促销
                    $info = $this->checkGoodsIsPromotion($this->local_id, $item['store_pid']);
                    if (!empty($info)){
                        $item['proPrice'] = number_format($info['price'], 2, '.', '');
                    }else{
                        $item['proPrice'] = '';
                    }
                    $item['url'] = url('Goods/detail',['id'=>$item['store_pid']]);
                    if ($images[$item['goods_id']]) {
                        $item['img'] = '/Uploads/'.$images[$item['goods_id']];
                    } else {
                        //没有图片上个默认的图片
                        $item['img'] = '/Public/Home/images/loading.gif';
                    }

                    // 判断闪购
                    $flashGoods = $GoodsModel->checkGoodsIsStarBuy($item['store_pid']);
                    if (!empty($flashGoods)) {
                        $list[$key]['flashPrice'] = $flashGoods['promotion_price'];
                        $list[$key]['store'] = $flashGoods['initnum'];
                        $list[$key]['freez'] = 0;
                    }else{
                        $list[$key]['flashPrice'] = '';
                    }
                    // 判断组合促销
                    $checkProductIsGroupPromotion = checkProductIsGroupPromotion($item['store_pid'], $item['local_id']);
                    $list[$key]['groupPromotion'] = $checkProductIsGroupPromotion;
                }
            }
            $this->assign('keywords', $keywords);
            $this->assign('list', $list);
            if (IS_AJAX) {
                $data = [
                    'p'=>$p,
                    'num'=>$num,
                    'order_field'=>$order_field,
                    'order'=>$sunxu,
                    'totalNum'=>$count,
                    'totalPage'=>$totalPage,
                    'list'=>$list,
                ];
                $this->ajaxReturn(['status'=>true, 'message'=>'获取成功', 'data'=>$data]);
                exit;
            }
            $this->display();
        }
    }

    /**
     * 热门关键字的搜索
     */
    public function _hotSearch($hot_key) {
        $keywords = M('store_search')->where(['local_id'=>$this->local_id, 'id'=>$hot_key, 'state'=>'1'])->getField('keywords');
        $keywords = json_decode($keywords, true);
        if (count($keywords) > 1) {
            foreach ($keywords as $item){
                if (!empty($item)) {

                    $where .= " a.p_name like '%".$item."%' OR ";
                }
            }
            $where = substr($where, 0, -3);
        } else {
            $where = " a.p_name like '%".$keywords[0]."%' ";
        }
        return $where;
    }


    public function getProductsImgByGoodsIds($goodsids) {
        if(!$goodsids || !is_array($goodsids)){
            return '';
        }
        $images = M('b2c_goods a')
            ->join(C('DB_PREFIX').'image_image b on a.image_default_id=b.image_id', 'LEFT')
            ->field('a.goods_id,b.m_url')
            ->where(array('goods_id'=>['in', $goodsids]))
            ->select();
        $temp = [];
        foreach ($images as $item) {
            $temp[$item['goods_id']] = $item['m_url'];
        }
        return $temp;
    }
}